import { LocalstorageDataManage } from './localstoreage/localstoreageDataManage';
import { businsessHttpServer } from './http/http-server';
import axios from 'axios';

export class TimeManager {
    public static current = new TimeManager();
    constructor() {
        if (!this.serverTimingOffset) {
            const timer = setInterval(() => {
                Promise.resolve().then(() =>
                    businsessHttpServer("/api/system/getServerTime").get().then((data) => {
                        clearInterval(timer);
                        const result = data.data.data;
                        TimeManager.current.serverTimingOffset = new Date().getTime() - result.serverTime;
                    })).catch(ex => { console.log(ex) })
            }, 5000)
        }
    }
    getServerTime() {
        return this.getLocalTime() - this.serverTimingOffset;
    }
    getLocalTime() {
        return new Date().getTime();
    }
    getNowTimeToBusinessTime() {
        let store = LocalstorageDataManage.current.getStore();
        let lastBusinessTime = new Date();
        lastBusinessTime.setHours(store && store.setting && store.setting.businessDuration || 0);
        lastBusinessTime.setMinutes(0);
        lastBusinessTime.setSeconds(0);
        let startTime = lastBusinessTime.getTime() < new Date().getTime() ? lastBusinessTime.getTime() : lastBusinessTime.getTime() - 24 * 60 * 60 * 1000;
        let endTime = startTime + 24 * 60 * 60 * 1000;
        return {
            startTime: startTime,
            endTime: endTime
        }
    }
    serverTimingOffset = 0;
}